package com.wangsd.web.coupon.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.wangsd.common.basicbean.Result;
import com.wangsd.web.MyController;
import com.wangsd.web.coupon.entity.TOrder;
import com.wangsd.web.coupon.service.TOrderService;
import com.wangsd.web.coupon.service.WxMiniPayService;
import com.wangsd.web.sys.entity.SysUser;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

import static com.wangsd.common.enums.ResultCode.MINI_APP_ORDER_NOT_EXIST;
import static com.wangsd.common.enums.ResultCode.PRARM_NOT_NULL;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author generator
 * @since 2019-09-26
 */
@Slf4j
@RestController
@RequestMapping("/coupon/tOrder")
public class TOrderController extends MyController {

    @Autowired
    TOrderService orderService;

    @Autowired
    TOrderService tOrderService;

    @Autowired
    WxMiniPayService wxMiniPayService;

    @PostMapping("/selectList/{pageNum}/{pageSize}")
    @ApiOperation(value = "查询订单列表", notes = "查询订单列表", httpMethod = "POST")
    public Result selectList(@PathVariable Integer pageNum,
                             @PathVariable Integer pageSize,
                             @RequestBody @ApiParam(name = "tOrder", value = "传入json格式") TOrder tOrder) {
        SysUser loginUser = getUserInfo();

        String code = loginUser.getCode();
        if (tOrder.getCode() != null) {
            code = tOrder.getCode();
        }
        IPage<TOrder> resultList = orderService.selectPage(code, pageNum, pageSize, tOrder);

        Map statistics = orderService.selectListStatistics(tOrder,loginUser.getCode());
        Map map = new HashMap();
        map.put("pageInfo",resultList);
        map.put("statistics",statistics);
        return Result.success(map);
    }

    @ApiOperation(value = "更新物流信息", notes = "更新物流信息", httpMethod = "POST")
    @PostMapping("/updateExpress")
    public Result updateExpress(@RequestBody TOrder tOrder) {
        if (tOrder.getId() == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "订单id" + PRARM_NOT_NULL.getMessage());
        }
        if (tOrder.getExpressNo() == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "物流单号" + PRARM_NOT_NULL.getMessage());
        }
        if (tOrder.getExpressName() == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "物流名称" + PRARM_NOT_NULL.getMessage());
        }
        tOrder.setExpressStatus(1);
        orderService.updateById(tOrder);
        return Result.success();
    }

    /**
     * 微信退款调用
     *
     * @return
     */
    @ApiOperation(value = "微信退款调用", notes = "微信退款调用", httpMethod = "POST")
    @PostMapping("/refund")
    public Object refund(String orderId, HttpServletRequest request) {

        if (orderId == null) {
            return new Result(9000, "缺少参数", "");
        }
        TOrder tOrder = tOrderService.getOne(new QueryWrapper<TOrder>().eq("transaction_id", orderId));
        if (tOrder == null) {
            return Result.message(MINI_APP_ORDER_NOT_EXIST);
        }

        String object = null;
        try {
            /*2：商家券退款，其他是商品退款*/
            if("30".equals(tOrder.getTradeType())){
                object = wxMiniPayService.businessRefund(tOrder, getMiniAppid(), orderId, request);
            }else{
                object = wxMiniPayService.refund(tOrder, getMiniAppid(), orderId, request);
            }
        } catch (WxPayException e) {
            log.error("refund", e);
            return Result.fail(e.getCustomErrorMsg());
        } catch (Exception e) {
            log.error("refund", e);
            return Result.fail(e.getMessage());
        }

        if ("noAuth".equals(object)) {
            return Result.fail("无法发起退款！");
        } else if (object.contains("ERROR") || object.contains("error")) {
            return Result.fail(object);
        }

        return Result.success("退款成功！！");
    }
}

